﻿#region << 版 本 注 释 >>
/*----------------------------------------------------------------
// Copyright (C) 2021 kingerrobot
// 版权所有。 
//
// 文件名：BWmsOutOrderMaster
// 文件功能描述：
//
// 创建者：名字 (zzl)
// 时间：2021/12/21 15:55:51
//
// 修改人：
// 时间：
// 修改说明：
// 版本：V1.0.0
//----------------------------------------------------------------*/
#endregion
using K8.MDCBB;
using KingerRobot.MexicoSailunMDC.Dao;
using Microsoft.IdentityModel.Tokens;

namespace KingerRobot.MexicoSailunMDC.SpiService;

internal class BWmsOutOrderMaster : IWmsOutOrderMaster
{
    private readonly static IWmsOutOrderSummary _WmsOutOrderSummary = new BWmsOutOrderSummary();
    private readonly static IBakWmsOutOrderMaster _BakWmsOutOrderMaster = new BBakWmsOutOrderMaster();
    private readonly static IWmsOutOrderDetail _WmsOutOrderDetail = new BWmsOrderOrderDetail();
    private readonly static IProdSkuProduct _ProdSkuProduct = new BProdSkuProduct();
    private readonly static IWmsOutOrderSummarySafe _WmsOutOrderSummarySafe = new BWmsOutOrderSummarySafe();
    private readonly static IWcsEquipLoc _WcsEquipLoc = new BWcsEquipLoc();
    private readonly static IRcsEquipCuring _RcsEquipCuring = new BRcsEquipCuring();



    public int BakAndDeleteOutOrderByTask(POWcsTask task)
    {
        var db = Db.Default;
        var masterId = task.MasterId;

        var result = 0;
        var summaryList = db.WmsOutOrderSummarys.Where(t => t.MasterId == masterId).ToList();
        var summaryId = summaryList.Where(t => t.Id == task.SummaryId).FirstOrDefault()?.Id ?? 0;
        //证明是单模请料 删除主从表信息
        if (summaryList is not null && summaryList.Count == 1)
        {    //删除从表
            _WmsOutOrderSummary.BakAndDeleteOutOrderSummary(summaryId);
            //删除主表
            var master = db.WmsOutOrderMasters.Where(t => t.Id == masterId).FirstOrDefault();
            if (master is not null)
            {
                result = BakAndDeleteOutOrderMaster(master);
            }
        }
        else//双模请料  只删除对应的从表信息
        {
            result = _WmsOutOrderSummary.BakAndDeleteOutOrderSummary(summaryId);
        }
        return result;
    }
    public POWmsOutOrderMaster GetOutOrderMasterById(long id)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderMasters.Where(t => t.Id == id).FirstOrDefault();
        return result;
    }

    public long AddOutOrderMaster(int orderType, long? directLoc = null, int directDelivery = 0, int priority = 12, string mesOrderNo = "")
    {
        var db = Db.Default;
        var orderId = XID.Nextval;
        var num = db.WmsOutOrderMasters.Insert(new POWmsOutOrderMaster()
        {
            Id = orderId,
            MesOrderNo = mesOrderNo,
            OrderCode = K8.LSF.Client.CodeValue(new DateTime(), "OutOrder"),
            OrderType = orderType,
            OrderStatus = (int)EnumCodeOutOrderStatus.Create,
            DirectDelivery = directDelivery,
            DirectLoc = directLoc,
            OrderPriority = priority
        });
        if (num == 0)
        {
            return 0;
        }
        return orderId;
    }
    public int BakOutOderMaster(POWmsOutOrderMaster wmsOutOrderMaster)
    {
        if (wmsOutOrderMaster is null)
        {
            return 0;
        }
        if (_BakWmsOutOrderMaster.GetBakWmsOutOrderMasterById(wmsOutOrderMaster.Id ?? 0) is not null)
        {
            return 0;
        }
        var db = Db.Default;
        var result = 0;
        try
        {
            result = db.BakWmsOutOrderMasters.CopyFrom(wmsOutOrderMaster);
        }
        catch (Exception ex)
        {
            WriteLog(ex.ToString());
        }
        return result;
    }
    public int DeleteOutOderMaster(long? id)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderMasters.Where(t => t.Id == id).Delete();
        return result;
    }

    public int UpdateOutOrderFinish(long id, int finishMode)
    {
        var num = UpdateOutOrderMasterFinish(id, finishMode);

        // var num1 = _WmsOutOrderSummary.UpdateOutOrderSummaryFinish(id, finishMode);

        return num;
    }
    public int UpdateOutOrderMasterFinish(long id, int finishMode)
    {
        var db = Db.Default;
        var result = 0;
        var master = db.WmsOutOrderMasters.Where(t => t.Id == id).FirstOrDefault();

        master.FinishMode = finishMode;
        master.FinishTime = DateTime.Now;
        result = db.SaveChanges();
        return result;
    }


    public int BakAndDeleteOutOrderMaster(POWmsOutOrderMaster pOWmsOutOrderMaster)
    {
        if (pOWmsOutOrderMaster is null)
        {
            return 0;
        }
        var result = BakOutOderMaster(pOWmsOutOrderMaster);
        var id = pOWmsOutOrderMaster?.Id ?? 0;
        result += DeleteOutOderMaster(id);

        return result;
    }


    public int OutOrderFinishByBakTask(long masterId, long summaryId)
    {
        var result = 0;
        //var summary = _WmsOutOrderSummary.GetOutOrderSummaryById(summaryId);
        //if (summary != null)
        //{
        // 数据明细 备份删除
        result = _WmsOutOrderSummary.BakAndDeleteOutOrderSummary(summaryId);
        //}

        var master = GetOutOrderMasterById(masterId);

        if (master is not null && !_WmsOutOrderSummary.IsOutOrderSummaryByMasterId(masterId))
        {
            // 修改完成状态
            UpdateOutOrderFinish(masterId, (int)EnumCodeFinishMode.NormalEnd);

            // 主数据备份 删除
            result += BakAndDeleteOutOrderMaster(master);
        }

        return result;
    }


    public int OutOrderFinish(POWcsTask task)
    {
        if (task == null)
        {
            return 0;
        }
        var masterId = task.MasterId ?? 0;
        var summaryId = task.SummaryId ?? 0;
        var skuId = task.SkuId ?? 0;
        if (masterId == 0 || summaryId == 0)
        {
            return 0;
        }

        //var master = GetOutOrderMasterById(id);
        //if (master == null)
        //{
        //    return 0;
        //}


        var result = 0;
        var summary = _WmsOutOrderSummary.GetOutOrderSummaryById(summaryId);
        if (summary != null)
        {

            var loc = summary?.TargetLoc ?? 0L;
            var equip = _WcsEquipLoc.GetEquipIdByLocId(loc);
            var curing = _RcsEquipCuring.GetCuringById(equip);
            var isCuringCall = curing?.IsCuringCall ?? 0;
            // 异常信号 / 
            if (summary.Safe == 0 || (task?.TaskType == (int)EnumTaskType.Abnormal && isCuringCall != 0))
            {
                _WmsOutOrderSummarySafe.AddOutOrderSumarySafe(summary.Id.GetValueOrDefault(),
                    summary.TargetLoc.GetValueOrDefault(),
                    summary.Safe.GetValueOrDefault());
            }

            // 数据明细 备份删除
            result += _WmsOutOrderSummary.BakAndDeleteOutOrderSummary(summary.Id.GetValueOrDefault());
        }

        if (!_WmsOutOrderSummary.IsOutOrderSummaryByMasterId(masterId))
        {
            var master = GetOutOrderMasterById(masterId);
            // 修改完成状态
            UpdateOutOrderFinish(masterId, (int)EnumCodeFinishMode.NormalEnd);

            // 主数据备份 删除
            result += BakAndDeleteOutOrderMaster(master);
        }

        return result;
    }

    public int ReRequestMaterial(long masterId)
    {
        var summarys = _WmsOutOrderSummary.GetOutOrderSummaryByMasterId(masterId);
        var num = 0;
        foreach (var summary in summarys)
        {
            // 重新请料
            num += _WmsOutOrderSummary.ReRequestSummary(summary.Id.GetValueOrDefault());
        }

        num += UpdateMasterStatus(masterId, (int)EnumCodeOutOrderStatus.Create);

        return num;
    }

    public int UpdateMasterStatus(long id, int status)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderMasters.Where(t => t.Id == id).Update(new POWmsOutOrderMaster
        {
            OrderStatus = status,
            UpdateTime = DateTime.Now,
        });
        return db.SaveChanges();
    }
    public int UpdateMasterOrderPriority(long id, int priority)
    {
        var db = Db.Default;
        var result = db.WmsOutOrderMasters.Where(t => t.Id == id).Update(new POWmsOutOrderMaster
        {
            OrderPriority = priority,
            UpdateTime = DateTime.Now,
        });
        return db.SaveChanges();
    }

    public int QuartzBakAndDeleteOutOrder(DateTime dateTime)
    {
        var db = Db.Default;

        var result = 0;


        //找到超时24h的主表
        var dt1 = DateTime.Now.AddDays(-1);
        var dayMasterList = db.WmsOutOrderMasters.Where(t => t.CreateTime < dt1).ToList();
        //24以前的直接删除主从表
        foreach (var dayMaster in dayMasterList)
        {
            result = _WmsOutOrderSummary.BakAndDeleteOutOrderSummaryByMasterId(dayMaster.Id ?? 0, "超时自动删除");
            if (result > 0)
            {
                dayMaster.RemarkMemo = "超时自动删除";
                BakAndDeleteOutOrderMaster(dayMaster);
            }
        }




        //找到超时的主表列表
        var masterList = db.WmsOutOrderMasters.Where(t => t.CreateTime < dateTime).ToList();
        //筛选出不可删除的主表id
        var noBakMasterIds = db.WmsOutOrderSummarys.Where(t => t.RealCount > 0).Select(t => t.MasterId).ToList();
        //筛选出可以删除的主表id
        masterList = masterList.Where(t => !noBakMasterIds.Contains(t.Id)).ToList();

        foreach (var master in masterList)
        {
            result = _WmsOutOrderSummary.BakAndDeleteOutOrderSummaryByMasterId(master.Id ?? 0, "超时自动删除");
            if (result > 0)
            {
                master.RemarkMemo = "超时自动删除";
                BakAndDeleteOutOrderMaster(master);
            }
        }

        return result;
    }

    //public int BakAndDeleteOutOrderMaster(POWmsOutOrderMaster pOWmsOutOrderMaster)
    //{
    //    var result = BakOutOderMaster(pOWmsOutOrderMaster);
    //    var id = pOWmsOutOrderMaster.Id.GetValueOrDefault();
    //    result += DeleteOutOderMaster(id);

    //    return result;
    //}

}
